package main

import (
	"9-json/model"
	"encoding/json"
	"net/http"
)

// -- json --
//  1. field name 映射	-> tag
//  2. 类型映射		    ->
//  3. 未知结构处理		-> map[string]any  []any
//  4. encoder decoder 	适合 stream - json
//     marshal unmarshal 适合 bytes\string - json
func main() {
	http.HandleFunc("/json",
		func(writer http.ResponseWriter, request *http.Request) {
			method := request.Method
			switch method {
			case http.MethodPost:
				// 写入值, 指针结构
				c := new(model.Company)
				err := json.NewDecoder(request.Body).Decode(c)
				if err != nil {
					http.Error(writer, http.StatusText(http.StatusInternalServerError),
						http.StatusInternalServerError)
					return
				}

				err = json.NewEncoder(writer).Encode(c)
				if err != nil {
					http.Error(writer, http.StatusText(http.StatusInternalServerError),
						http.StatusInternalServerError)
					return
				}
			default:
				http.Error(writer, http.StatusText(http.StatusMethodNotAllowed),
					http.StatusMethodNotAllowed)
			}
		})

	// 启动服务器
	http.ListenAndServe("localhost:8080", nil)
}
